package chenji.gunapi.bullet.player;

import org.bukkit.entity.Player;

import chenji.gunapi.events.MouseClickEvent.MouseButtonType;
import chenji.gunapi.gun.Gun;
import chenji.gunapi.gun.ReloadHandler;
import chenji.gunapi.gun.Sight;
import chenji.gunapi.gun.SoundHandler;

/**
 * @author ChenJi
 */
public class PlayerGun {
	private Player p;
	private Gun gun;
	private boolean isShooting;
	private ReloadHandler reloadhandler;
	private int lastShootTime;
	private int shootamount;
	private Sight sight;
	private boolean tempclose;
	private boolean alreadshoot;

	public PlayerGun(Player p, Gun gun, int amount) {
		this.p = p;
		this.gun = gun;
		SoundHandler s = gun.getSoundHandler();
		this.reloadhandler = gun.getReloadHandler().clone(s, p, amount);
		if (gun.canSights()) {
			sight = this.gun.getSights().clone(p);
		}

	}

	public Gun getGun() {
		return this.gun;
	}

	public Player getPlayer() {
		return this.p;
	}

	public void Task() {
		this.reloadhandler.tick();
		this.lastShootTime++;
		this.shootamount = this.getGun().getAlreadShootAmount(lastShootTime);
		if (this.tempclose) {
			if (!this.reloadhandler.isReloading()) {
				this.sight.open();
			}
		}
		if (this.isShooting) {
			if (this.alreadshoot && this.gun.autoShoot()) {
				return;
			}
			this.tryShoot();
		}

	}

	public void updateMouseEvent(MouseButtonType m, boolean state) {

		if (m.equals(MouseButtonType.LEFT)) {
			if (state) {
				this.isShooting = true;
				this.alreadshoot = false;
				this.tryShoot();
			} else {
				this.isShooting = false;
			}
		}
		if (this.gun.canSights()) {
			if (m.equals(MouseButtonType.RIGHT)) {
				if (state) {
					this.sight.chengeSight();
					this.tempclose = false;
				}
			}
		}
	}

	public void tryShoot() {
		if (this.reloadhandler.canShoot()) {
			this.shoot();
		} else {
			if (this.reloadhandler.getNowAmount() <= 0) {
				this.reloadhandler.reload();
			}
		}
	}

	private void shoot() {
		p.sendMessage(this.reloadhandler.getNowAmount() + "");
		this.reloadhandler.shoot();
		this.alreadshoot = true;
		this.shootamount++;
		this.lastShootTime = 0;
		this.getGun().shoot(p, this.shootamount);
	}

	public int getNowAmount() {
		return this.reloadhandler.getNowAmount();
	}

}
